AddCSLuaFile("cl_init.lua");
AddCSLuaFile("shared.lua");

include("shared.lua");

-- Called when the SENT is spawned.
function ENT:Initialize()
	self:DropToFloor();
	self:SetMoveType(MOVETYPE_NONE);
 	self:SetMaterial("models/wireframe");

 	self.LastUsed = CurTime();
end;

function ENT:AddResource(player,res,int)
    self.Costs[res] = self.Costs[res] -int;
	
    if (self.Costs[res] <= 0) then
        self.Costs[res] = nil;
    end;
	
	local text = ":";
	for k, v in pairs(self.Costs) do
		text = text .. " " .. k .. " (x" .. v .. ")";
	end
	
	self.Entity:SetNetworkedString("Resources", text);
end

function ENT:Setup(model, resclass)
    self.Entity:SetModel(model)
    self.ResultClass = resclass

	self.Entity:PhysicsInit( SOLID_VPHYSICS )
	self.Entity:SetMoveType( MOVETYPE_VPHYSICS )
	self.Entity:SetSolid( SOLID_VPHYSICS )

	self.Entity:SetColor(255, 255, 255, 255)

 	local phys = self.Entity:GetPhysicsObject()
 	if phys != NULL and phys then 
		phys:EnableMotion(false) 
	end
end

function ENT:Finish()
    local ent = ents.Create(self.ResultClass)	
	
	if self.NormalProp == true then
		ent.NormalProp = true
	end
	
    ent:SetPos(self:GetPos())
    ent:SetAngles(self:GetAngles())
    ent:SetModel(self:GetModel())
	ent.Player = self.Player
	ent:SetNetworkedString('Name', self.Name)
    ent:Spawn()
	ent.owner = self.Player;
    ent:Fadein()
 
    self.Entity.Player.HasBuildingSite = false
	self.Entity:Remove()
end

function ENT:Use(player)
    if CurTime() - self.LastUsed < 0.5 then return end
	self.LastUsed = CurTime()
	--if !(SPropProtection.PlayerIsPropOwner(player, self.Entity) or SPropProtection.IsBuddy(player, self.Entity)) and !(tonumber(SPropProtection["Config"]["use"]) != 1) then return end

    for k,v in pairs(self.Costs) do
        if player:GetResource(k) >= 0 then
            if player:GetResource(k) < v then
                self:AddResource(player,k,player:GetResource(k))
                player:DecResource(k,player:GetResource(k))
            else
                self:AddResource(player,k,v)
                player:DecResource(k,v)
            end
        end
    end
    if table.Count(self.Costs) > 0 then
        local str = "You need: "
        for k,v in pairs(self.Costs) do
            str = str..k.." ("..v.."x)  "
        end
        str = str.." to finish."
        player:SendMessage(str,5,Color(255,255,255,255))
    else
        player:SendMessage("Finished!",3,Color(10,200,10,255))
		self:Finish()            
    end
end